package net.lwf.jaxb.service.maths.fraction;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.lwf.jaxb.service.JaxbService;
import net.lwf.jaxb.stubs.maths.fraction.Challenge;
import net.lwf.jaxb.stubs.maths.fraction.Data;
import net.lwf.jaxb.stubs.maths.fraction.Fractions;
import net.lwf.jaxb.stubs.maths.fraction.Grade;
import net.lwf.jaxb.stubs.maths.fraction.OperationType;

public class FractionDataService extends JaxbService {
	
	private static final String CONTEXT_PATH = "net.lwf.jaxb.stubs.maths.fraction";
	
	private String xmlFileName = "fractions/fractions.xml";
	
	private static Map<String, Data> fractionData;
	
	public Data getFractionData(String grade, String operation) {
		Data data = null;
		if(fractionData == null) {
			fractionData = new HashMap<String, Data>();
			this.init(grade, operation);
		}
		else if(!fractionData.containsKey(grade+operation)) {
			init(grade, operation);
		}
		data = fractionData.get(grade+operation);
		return data;
	}
	
	public List<String> getOperationTypes(String grade, String operation) {
		List<String> types = new ArrayList<String>();
		Data fractiondata = getFractionData(grade, operation);
		List<OperationType> types1 = fractiondata.getOperationType();
		for(OperationType operationtype: fractiondata.getOperationType()) {
			types.add(operationtype.getName());
		}
		return types;
	}
	
	public List<String> getOperationChallenges(String grade, String operation, String _operationtype) {
		List<String> challenges = new ArrayList<String>();
		Data fractiondata = getFractionData(grade, operation);
		for(OperationType operationtype: fractiondata.getOperationType()) {
			if(operationtype.getName().equalsIgnoreCase(_operationtype)) {
				for(Challenge challenge: operationtype.getChallenge()) {
					challenges.add(challenge.getName());
				}
			}
		}

		return challenges;
	}

	
	private void init(String grade, String operation) {
		Fractions list = (Fractions) loadedXmlData();
		List<Grade> grades = list.getGrade();
		for(Grade gradedata: grades) {
			if(gradedata.getGrade().equalsIgnoreCase(grade)) {
				List<Data> fractiondata = gradedata.getData();
				for(Data data: fractiondata) {
					if(data.getOperation().equalsIgnoreCase(operation)) {
						fractionData.put(grade+operation, data);
						return;
					}
				}
			}
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FractionDataService service = new FractionDataService();
		Data data = service.getFractionData("3", "comparison");
		System.out.println("Operation: "+data.getOperation());
		System.out.println("Numerator - From: " + data.getNumerator().getFrom() + ", To: " + data.getNumerator().getTo());

	}

	@Override
	public String getContextPath() {
		return CONTEXT_PATH;
	}

	@Override
	public String getXmlFileName() {
		return xmlFileName;
	}

}
